const querystring = require('querystring');
const { getPostData,formatGetToPostParams } = require('./util');
const handelBlogRouter = require('./router/blog');
const handelUserRouter = require('./router/user');
const { setRedis, getRedis } = require('./db/redis');
const accessLog  = require('./util/accessLog')

const serverHandel = async (req, res) => {
  // console.log(req.headers.host); 这里可以打开nginx proxy_set_header 配置
  req.path = req.url.split('?')[0];
  req.query = querystring.parse(req.url.split('?')[1]);
  req.cookie = formatGetToPostParams(req.headers.cookie)
  accessLog(req)
  let sessionId = req.cookie.sessionId;
  if(!sessionId){
    sessionId = `${Date.now()}_${Math.random()}`
    const currentTime = (new Date()).getTime()
    res.setHeader('Set-Cookie',`sessionId=${sessionId};expires=${new Date(currentTime+24*60*60*1000)};path=/;`)
    setRedis(sessionId,{})
  }
  req.sessionId = sessionId
  const sessionData = await getRedis(sessionId)
  if(sessionData === null){
    set(req.sessionId, {})
    req.session = {}
  } else {
    req.session = sessionData
  }
  
  res.setHeader('Content-type', 'application/json');
  getPostData(req, res).then((postData) => {
    req.body = postData;

    // 处理页面路由
    const blogResult = handelBlogRouter(req, res);
    if (blogResult) {
      blogResult.then((blogData) => {
        res.end(JSON.stringify(blogData));
      });
      return;
    }

    // 处理用户路由
    const userResult = handelUserRouter(req, res);
    if (userResult) {
      userResult.then((userData) => {
        res.end(JSON.stringify(userData));
      });
      return;
    }
    res.writeHead(404, { 'Content-Type': 'text/plain' }).end('404 Not Found');
  });
};
module.exports = serverHandel;
